package cn.kgc.utils;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.sql.SQLException;

/**
 * 增强类控制事务
 */
@Component("AopUtil")
@Aspect
public class AopUtil {
    @Autowired
    private TransactionUtil transactionUtil;

    @Pointcut("execution(* cn.kgc.service.AccountService.transfer(..))")
    public void pt(){}



    @Around("pt()")
    public void around(ProceedingJoinPoint joinPoint) throws SQLException {
        try {
            System.out.println("前置通知，开启事务");
            transactionUtil.beginTransaction();
            joinPoint.proceed();
            System.out.println("后置通知，提交事务");
            transactionUtil.commitTransaction();
        } catch (Throwable throwable) {
            System.out.println("异常增强，回滚事务");
            transactionUtil.rollbackTransaction();
            throwable.printStackTrace();
        } finally {
            System.out.println("最终增强，释放资源");
            transactionUtil.closeTransaction();
        }
    }
}
